package core

import (
	"area"
	"net"
	"region/config"
	"region/kernel"
	"share/app"
	"share/msg"
	"util/log"
	"util/parser"
)

var (
	regionMgr = &RegionMgr{}
)

type RegionMgr struct {
	mapinfo   *area.MapInfo
	cfg       *config.Config
	servSock  *ServSock
	appClient *app.AppClient
	mquit     chan bool
	runchan   chan bool
	regions   map[int32]kernel.Region
}

//初始化所有数据
func (r *RegionMgr) initAllInfo() {
	r.mapinfo = area.CreateMap()
	r.mapinfo.LoadMaps(r.cfg.Mappath)
	r.servSock = CreateServSock(r.cfg.ServIp, r.cfg.ServPort)
	r.appClient = app.CreateAppClient()
	r.regions = make(map[int32]kernel.Region)
}

func (r *RegionMgr) Start(ch chan bool, c *config.Config) {
	r.cfg = c
	r.mquit = ch
	r.runchan = make(chan bool)
	parser.LoadAllDef(r.cfg.Defpath)
	r.initAllInfo()
	r.run()
}

func (r *RegionMgr) run() {

	if err := r.servSock.Start(1); err != nil {
		panic("serv sock failed")
	}

	addr, _ := r.servSock.Addr().(*net.TCPAddr)

	r.appClient.Run(r.cfg.CenterIp, r.cfg.CenterPort, msg.AT_REGION, string(addr.IP.String()), addr.Port)

wait:
	for {
		select {
		case <-r.runchan:
			break wait
		}
	}

	r.appClient.Shutdown()
	r.mquit <- true
	log.TraceInfo("RegionMgr", "service quit")

}

func (r *RegionMgr) shutdown() {

	r.appClient.Close()
	r.appClient.Tcpconn = nil

	if r.servSock != nil {
		r.servSock.Close()

		r.servSock = nil
	}

	r.runchan <- true
}

func GetRegionMgr() *RegionMgr {
	return regionMgr
}

func ServiceQuit() {
	log.TraceInfo("RegionMgr", "shutdown")
	regionMgr.shutdown()
}
